﻿Imports System.Data.SqlClient
Imports CodeMatrix.Context
Imports System.Linq

Partial Class Apps_Shares_Uc_sub_menu_list
    Inherits System.Web.UI.UserControl

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Try
            If Not IsPostBack Then
                InitCtrl()
            End If
        Catch ex As Exception
            GenericHelper.ShowAlert(Me, ex.Message)
        End Try
    End Sub

    Sub InitCtrl()
        ' Set breadcrump
        Dim BreadCrumpBG As HtmlControl = Page.Master.FindControl("tdBreadCrump")
        Dim BreadCrump As Literal = Page.Master.FindControl("ltrBreadCrump")
        If Not Request.QueryString("del") Is Nothing Then
            CodeMatrix.Business.GenericData.SetBreadCrump(BreadCrumpBG, BreadCrump, 32)
        ElseIf Not Request.QueryString("edit") Is Nothing Then
            CodeMatrix.Business.GenericData.SetBreadCrump(BreadCrumpBG, BreadCrump, 31)
        Else
            CodeMatrix.Business.GenericData.SetBreadCrump(BreadCrumpBG, BreadCrump, 29)
        End If
    End Sub

    Protected Sub btnFilter_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnFilter.Click

        Try
            'Filter data
            gvDisplay.DataBind()
            gvDisplay.Sort("sub_menu_name", SortDirection.Ascending)
        Catch ex As Exception
            GenericHelper.ShowAlert(Me, ex.Message)
        End Try

    End Sub

    Protected Sub btnDelete_Click(ByVal sender As Object, ByVal e As System.EventArgs) 'Handles btnDelete.Click
        Try
            gvDisplaySrc.Delete()
            gvDisplay.DataBind()
        Catch ex As SqlException
            GenericHelper.ShowAlert(Me, _
                                    String.Format(Resources.Resource.MSG_CAUTION_DELETE_DEPEND_DATA, "") _
                                    )
        End Try
    End Sub

    Protected Sub gvDisplaySrc_Deleting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.SqlDataSourceCommandEventArgs) Handles gvDisplaySrc.Deleting

        Try
            ' ============================================
            ' Assign parameter to SQL statement to delete
            ' ============================================
            Dim keys As Int32() = CodeMatrix.Utilities.WebUiHelper.GetSelectedCheckBox(Of Int32)(gvDisplay, "sub_menu_code", "icbItem")
            Dim ctx As DataClassesDataContext = New DataClassesDataContext
            For Each i In ctx.stp_auth_departments.Where(Function(f) keys.Contains(f.sub_menu_code))
                Dim sub_menu_name = ctx.stp_sub_menus.SingleOrDefault(Function(f) f.sub_menu_code = i.sub_menu_code).sub_menu_name
                Throw New Exception(String.Format(Resources.Resource.MSG_CAUTION_DELETE_DEPEND_DATA, sub_menu_name))

            Next

            If keys.Length > 0 Then
                e.Command.Parameters("@cid").Value = CodeMatrix.Utilities.CodeHelper.CreateSeriesOfParameters(keys)
                Dim value As New OrderedDictionary()
                value.Add(e.Command.Parameters("@pid").Value, e.Command.Parameters("@cid").Value)
                GenericHelper.GenerateScript(GenerateScriptLogType.Delete, LogMenuType.stp_sub_menu, value)
            Else
                e.Cancel = True
            End If
        Catch ex As Exception
            e.Cancel = True
            GenericHelper.ShowAlert(Me, ex.Message)
        End Try
    End Sub

    Protected Sub btnUpdate_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnUpdate.Click

        Try
            ' ============================================================================
            ' Update whole data in rows
            ' ============================================================================
            Dim stmt = "UPDATE [stp_sub_menu]" & _
                                "SET " & _
                                "      [sub_menu_name] = @sub_menu_name" & _
                                "      ,[sub_menu_url] = @sub_menu_url" & _
                                "      ,[type_code] = @type_code" & _
                                "      ,[sub_menu_status] = @sub_menu_status" & _
                                "      ,[staff_code_update] = @staff_code_update" & _
                                "      ,[update_datetime] = getdate()" & _
                                Environment.NewLine & _
                                " WHERE sub_menu_code = @sub_menu_code"

            Using c As New SqlConnection(CodeMatrix.Utilities.CodeHelper.ConnectionString)

                c.Open()
                For Each i As ListViewDataItem In gvDisplay.Items

                    Dim txtSubNameName = CType(i.FindControl("txtSubNameName"), TextBox)
                    Dim ddlType = CType(i.FindControl("ddlType"), DropDownList)
                    Dim txtURL = CType(i.FindControl("txtURL"), TextBox)
                    Dim ddlStatus = CType(i.FindControl("ddlStatus"), DropDownList)
                    Dim sub_menu_code = CType(i.FindControl("hideSubMenuCode"), HiddenField).Value 'gvDisplay.DataKeys(0).Value(i.DataItemIndex Mod 20)

                    ' ================================================
                    ' For updating
                    ' ================================================
                    Dim _sub_menu_name As String
                    Dim _type_code As Integer
                    Dim _sub_menu_url As String
                    Dim _sub_menu_status As Integer
                    Dim _sub_menu_code As Integer

                    _sub_menu_name = txtSubNameName.Text
                    _type_code = ddlType.SelectedValue
                    _sub_menu_url = txtURL.Text
                    _sub_menu_status = ddlStatus.SelectedValue
                    _sub_menu_code = sub_menu_code

                    Dim cmd = New SqlCommand(stmt, c)

                    ' ==================================================================
                    ' Generate log script
                    ' ==================================================================
                    Dim logDesc As String = ""
                    logDesc = "ผู้ใช้งาน " & HttpContext.Current.Session("staff_no") & " แก้ไขข้อมูลในตาราง " & LogMenuType.stp_sub_menu.ToString() & " "
                    logDesc &= "คอลัมน์: sub_menu_name ข้อมูลใหม่: " & _sub_menu_name & ", "
                    logDesc &= "คอลัมน์: sub_menu_url ข้อมูลใหม่: " & _sub_menu_url & ", "
                    logDesc &= "คอลัมน์: type_code ข้อมูลใหม่: " & _type_code & ", "
                    logDesc &= "คอลัมน์: sub_menu_status ข้อมูลใหม่: " & _sub_menu_status
                    CodeMatrix.Business.GenericData.WriteLog(logDesc, 9, "U", Session("staff_code"))
                    'New SqlParameter("@menu_system_code", sub_menu_code), _
                    cmd.Parameters.AddRange( _
                            New SqlParameter() { _
                            New SqlParameter("@sub_menu_name", _sub_menu_name), _
                            New SqlParameter("@sub_menu_url", _sub_menu_url), _
                            New SqlParameter("@type_code", _type_code), _
                            New SqlParameter("@sub_menu_status", _sub_menu_status), _
                            New SqlParameter("@staff_code_update", Session("staff_code")), _
                            New SqlParameter("@sub_menu_code", _sub_menu_code)} _
                    )

                    Dim rs = cmd.ExecuteNonQuery()
                Next

            End Using

            gvDisplay.DataBind()
        Catch ex As Exception
            GenericHelper.ShowAlert(Me, ex.Message)
        End Try

    End Sub

    Protected Sub gvDisplaySrc_Selecting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.SqlDataSourceSelectingEventArgs) Handles gvDisplaySrc.Selecting

        Try
            If Not IsPostBack Then

                e.Cancel = True
            Else
                e.Command.Parameters("@main_system_code").Value = ddlSystem.SelectedValue
                e.Command.Parameters("@menu_system_code").Value = ddlSystemMenu.SelectedValue
                e.Command.Parameters("@type_code").Value = ddlCategory.SelectedValue
                e.Command.Parameters("@sub_menu_status").Value = ddlStatus.SelectedValue
            End If
        Catch ex As Exception
            GenericHelper.ShowAlert(Me, ex.Message)
        End Try

    End Sub

    Protected Sub gvDisplay_Sorting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ListViewSortEventArgs) Handles gvDisplay.Sorting

        Try
            If (String.IsNullOrEmpty(e.SortExpression)) Then
                Dim oldSortCol As Image = gvDisplay.FindControl(gvDisplay.SortExpression)
                If Not oldSortCol Is Nothing Then oldSortCol.Visible = False
            Else
                Dim oldSortCol As Image = gvDisplay.FindControl(gvDisplay.SortExpression)
                Dim newSortCol As Image = gvDisplay.FindControl(e.SortExpression)

                If (Not oldSortCol Is Nothing) Then oldSortCol.Visible = False
                If (Not newSortCol Is Nothing) Then
                    newSortCol.Visible = True
                    If e.SortDirection = SortDirection.Ascending Then
                        newSortCol.ImageUrl = "../images/btn_down.png"
                    Else
                        newSortCol.ImageUrl = "../images/btn_up.png"
                    End If
                End If
            End If
        Catch ex As Exception
            GenericHelper.ShowAlert(Me, ex.Message)
        End Try

    End Sub
End Class
